package com.niodata.dt.fs.us3;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

public class Us3OutputStream extends OutputStream {

  private final OutputStream backendOutput;
  private final File tmpFile;
  private final Us3Uploader uploader;
  private volatile boolean closed = false;


  public Us3OutputStream(Us3Uploader uploader) {
    String tmpPath = System.getProperty("user.dir") + "/.us3tmp/" + UUID.randomUUID();
    tmpFile = new File(tmpPath);
    if (!tmpFile.getParentFile().exists()) {
      tmpFile.getParentFile().mkdirs();
    }
    try {
      backendOutput = new FileOutputStream(tmpFile);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
    this.uploader = uploader;
  }

  @Override
  public void write(int b) throws IOException {
    backendOutput.write(b);
  }

  public void write(byte[] b, int offset, int length) throws IOException {
    backendOutput.write(b, offset, length);
  }

  @Override
  public void write(byte[] b) throws IOException {
    backendOutput.write(b);
  }

  @Override
  public void flush() throws IOException {
    backendOutput.flush();
  }


  @Override
  public void close() throws IOException {
    if (closed) {
      return;
    }
    try {
      backendOutput.close();
      closed = true;
      uploader.put(tmpFile);
    } finally {
      tmpFile.delete();
    }
    //upload or append
  }


}
